package com.yygo.webapp.controller.loanrequest;

import com.yygo.Constants;
import com.yygo.model.LoanRequest;
import com.yygo.model.User;
import com.yygo.service.LoanRequestManager;
import com.yygo.service.UserManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * Created by tiansha on 2015/8/30.
 */
@Controller
@RequestMapping("/batchAudit")
public class BatchAuditController extends BaseLoanRequestFormController {

    @Autowired
    private LoanRequestManager loanRequestManager;

    @Autowired
    private UserManager userManager;

    @RequestMapping(method = RequestMethod.GET)
    public String batchExport(Model model, HttpServletRequest request, @RequestParam(required = true, value = "selectedIds") Long[] selectedIds, Principal principal) throws IllegalAccessException {
        User loginUser = userManager.getUserByUsername(principal.getName());
        if (!loginUser.hasRole(Constants.Bank_USER_ROLE)) {
            throw new AccessDeniedException("You have no right to batch audit requests");
        }

        for (Long id : selectedIds) {
            LoanRequest loanRequest = loanRequestManager.loadWholeLoanRequest(id);
            handleAction(ACTION_bankCreditApprove, loanRequest, request.getLocale(), loginUser);
            loanRequestManager.saveLoanRequest(loanRequest);
        }

        return "redirect:/myloanrequests?phase=bank_credit_audit";
    }

}
